<template>
  <div class="edit-resume">
    <div class="header">
      <h2>编辑简历</h2>
      <div class="actions">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" @click="saveResume" :loading="saving">保存修改</el-button>
      </div>
    </div>

    <div class="loading" v-if="loading">
      <el-spinner size="large" />
      <p>加载简历数据中...</p>
    </div>

    <div class="content" v-else>
      <el-row :gutter="30">
        <!-- 左侧编辑区 -->
        <el-col :span="12">
          <div class="edit-section">
            <el-form :model="resumeForm" label-width="100px">
              <el-form-item label="简历标题">
                <el-input v-model="resumeForm.title" placeholder="请输入简历标题" />
              </el-form-item>
              
              <el-form-item label="选择模板">
                <el-select v-model="resumeForm.templateType" placeholder="选择模板">
                  <el-option label="经典模板" value="classic" />
                  <el-option label="现代简约" value="modern" />
                  <el-option label="创意设计" value="creative" />
                </el-select>
              </el-form-item>
            </el-form>

            <!-- 个人信息 -->
            <el-card class="section-card">
              <template #header>
                <h3>个人信息</h3>
              </template>
              <el-form :model="resumeData.personal" label-width="80px">
                <el-form-item label="姓名">
                  <el-input v-model="resumeData.personal.name" />
                </el-form-item>
                <el-form-item label="职位">
                  <el-input v-model="resumeData.personal.title" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="resumeData.personal.email" />
                </el-form-item>
                <el-form-item label="电话">
                  <el-input v-model="resumeData.personal.phone" />
                </el-form-item>
                <el-form-item label="地址">
                  <el-input v-model="resumeData.personal.location" />
                </el-form-item>
                <el-form-item label="个人简介">
                  <el-input type="textarea" v-model="resumeData.personal.summary" rows="3" />
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 工作经历 -->
            <el-card class="section-card">
              <template #header>
                <div class="section-header">
                  <h3>工作经历</h3>
                  <el-button size="small" @click="addExperience">添加</el-button>
                </div>
              </template>
              <div v-for="(exp, index) in resumeData.experience" :key="index" class="experience-item">
                <el-form :model="exp" label-width="80px">
                  <el-form-item label="公司">
                    <el-input v-model="exp.company" />
                  </el-form-item>
                  <el-form-item label="职位">
                    <el-input v-model="exp.position" />
                  </el-form-item>
                  <el-form-item label="时间">
                    <el-input v-model="exp.duration" placeholder="如：2020-2023" />
                  </el-form-item>
                  <el-form-item label="描述">
                    <el-input type="textarea" v-model="exp.description" rows="3" />
                  </el-form-item>
                  <el-button size="small" type="danger" @click="removeExperience(index)">删除</el-button>
                </el-form>
                <el-divider v-if="index < resumeData.experience.length - 1" />
              </div>
            </el-card>

            <!-- 教育背景 -->
            <el-card class="section-card">
              <template #header>
                <div class="section-header">
                  <h3>教育背景</h3>
                  <el-button size="small" @click="addEducation">添加</el-button>
                </div>
              </template>
              <div v-for="(edu, index) in resumeData.education" :key="index" class="education-item">
                <el-form :model="edu" label-width="80px">
                  <el-form-item label="学校">
                    <el-input v-model="edu.school" />
                  </el-form-item>
                  <el-form-item label="专业">
                    <el-input v-model="edu.degree" />
                  </el-form-item>
                  <el-form-item label="时间">
                    <el-input v-model="edu.duration" placeholder="如：2016-2020" />
                  </el-form-item>
                  <el-form-item label="GPA">
                    <el-input v-model="edu.gpa" placeholder="如：3.8/4.0" />
                  </el-form-item>
                  <el-button size="small" type="danger" @click="removeEducation(index)">删除</el-button>
                </el-form>
                <el-divider v-if="index < resumeData.education.length - 1" />
              </div>
            </el-card>
          </div>
        </el-col>

        <!-- 右侧预览区 -->
        <el-col :span="12">
          <div class="preview-section">
            <h3>简历预览</h3>
            <div class="preview-container">
              <div class="resume-preview">
                <div class="preview-header">
                  <h2>{{ resumeData.personal.name || '您的姓名' }}</h2>
                  <p>{{ resumeData.personal.title || '职位' }}</p>
                </div>
                <div class="preview-contact">
                  <p>{{ resumeData.personal.email || '邮箱' }}</p>
                  <p>{{ resumeData.personal.phone || '电话' }}</p>
                  <p>{{ resumeData.personal.location || '地址' }}</p>
                </div>
                <div v-if="resumeData.personal.summary" class="preview-summary">
                  <h4>个人简介</h4>
                  <p>{{ resumeData.personal.summary }}</p>
                </div>
                <div v-if="resumeData.experience.length" class="preview-experience">
                  <h4>工作经历</h4>
                  <div v-for="exp in resumeData.experience" :key="exp.company" class="exp-item">
                    <h5>{{ exp.position }} - {{ exp.company }}</h5>
                    <p class="duration">{{ exp.duration }}</p>
                    <p>{{ exp.description }}</p>
                  </div>
                </div>
                <div v-if="resumeData.education.length" class="preview-education">
                  <h4>教育背景</h4>
                  <div v-for="edu in resumeData.education" :key="edu.school" class="edu-item">
                    <h5>{{ edu.degree }} - {{ edu.school }}</h5>
                    <p class="duration">{{ edu.duration }}</p>
                    <p v-if="edu.gpa">GPA: {{ edu.gpa }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getResumeById as getResume, updateResume } from '@/api/resume'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const saving = ref(false)
const resumeId = ref(route.params.id)

const resumeForm = reactive({
  title: '',
  templateType: 'modern'
})

const resumeData = reactive({
  personal: {
    name: '',
    title: '',
    email: '',
    phone: '',
    location: '',
    summary: ''
  },
  experience: [],
  education: []
})

const addExperience = () => {
  resumeData.experience.push({
    company: '',
    position: '',
    duration: '',
    description: ''
  })
}

const removeExperience = (index) => {
  resumeData.experience.splice(index, 1)
}

const addEducation = () => {
  resumeData.education.push({
    school: '',
    degree: '',
    duration: '',
    gpa: ''
  })
}

const removeEducation = (index) => {
  resumeData.education.splice(index, 1)
}

const loadResume = async () => {
  try {
    loading.value = true
    console.log('加载简历ID:', resumeId.value)
    
    const response = await getResume(resumeId.value)
    console.log('加载的简历数据:', response)
    
    const resume = response.data || response
    
    // 设置基本信息
    resumeForm.title = resume.title || ''
    resumeForm.templateType = resume.templateType || 'modern'
    
    // 解析简历内容
    let content = {}
    if (typeof resume.content === 'string') {
      try {
        content = JSON.parse(resume.content)
      } catch (e) {
        console.error('解析简历内容失败:', e)
        content = {}
      }
    } else if (resume.content) {
      content = resume.content
    }
    
    // 设置个人信息
    Object.assign(resumeData.personal, {
      name: '',
      title: '',
      email: '',
      phone: '',
      location: '',
      summary: '',
      ...content.personal
    })
    
    // 设置工作经历
    resumeData.experience.splice(0, resumeData.experience.length)
    if (content.experience && Array.isArray(content.experience)) {
      resumeData.experience.push(...content.experience)
    }
    
    // 设置教育背景
    resumeData.education.splice(0, resumeData.education.length)
    if (content.education && Array.isArray(content.education)) {
      resumeData.education.push(...content.education)
    }
    
    console.log('解析后的简历数据:', {
      form: resumeForm,
      data: resumeData
    })
    
  } catch (error) {
    console.error('加载简历失败:', error)
    ElMessage.error('加载简历失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

const saveResume = async () => {
  if (!resumeForm.title) {
    ElMessage.error('请输入简历标题')
    return
  }

  if (!resumeData.personal.name) {
    ElMessage.error('请填写姓名')
    return
  }

  saving.value = true
  
  try {
    // 准备提交数据
    const submitData = {
      title: resumeForm.title,
      templateType: resumeForm.templateType,
      content: JSON.stringify(resumeData)
    }
    
    console.log('提交修改数据:', submitData)
    
    // 调用后端API更新
    const result = await updateResume(resumeId.value, submitData)
    console.log('后台更新结果:', result)
    
    ElMessage.success(`简历"${submitData.title}"修改成功！`)
    
    // 跳转到简历列表
    setTimeout(() => {
      router.push('/resumes')
    }, 1000)
    
  } catch (error) {
    console.error('保存失败详情:', error)
    
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足，请检查登录状态')
    } else if (error.code === 'ECONNREFUSED' || error.message?.includes('Network Error')) {
      ElMessage.error('无法连接到后端服务，请确保后端已启动')
    } else {
      ElMessage.error(error.response?.data?.message || error.message || '保存失败，请重试')
    }
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadResume()
})
</script>

<style scoped>
.edit-resume {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.header h2 {
  margin: 0;
  color: #333;
}

.actions {
  display: flex;
  gap: 10px;
}

.loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  gap: 20px;
}

.content {
  margin-top: 20px;
}

.edit-section {
  max-height: 80vh;
  overflow-y: auto;
  padding-right: 10px;
}

.section-card {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
}

.experience-item,
.education-item {
  margin-bottom: 20px;
}

.preview-section {
  position: sticky;
  top: 20px;
}

.preview-section h3 {
  margin-bottom: 20px;
  color: #333;
}

.preview-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  height: 80vh;
  overflow-y: auto;
}

.resume-preview {
  padding: 40px;
  background: white;
  font-family: Arial, sans-serif;
  line-height: 1.6;
}

.preview-header h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 28px;
}

.preview-header p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 18px;
}

.preview-contact {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #409eff;
}

.preview-contact p {
  margin: 5px 0;
  color: #666;
}

.preview-summary,
.preview-experience,
.preview-education {
  margin-bottom: 30px;
}

.preview-summary h4,
.preview-experience h4,
.preview-education h4 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 18px;
  border-bottom: 1px solid #409eff;
  padding-bottom: 5px;
}

.exp-item,
.edu-item {
  margin-bottom: 20px;
}

.exp-item h5,
.edu-item h5 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 16px;
}

.duration {
  color: #666;
  font-size: 14px;
  margin: 0 0 10px 0;
}

.preview-summary p {
  color: #333;
  margin: 0;
}
</style> 